import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:jyofservice/bean/LevelData.dart';
import 'package:jyofservice/bean/Node.dart';
import 'package:jyofservice/bean/order_person_entity.dart';
import 'package:jyofservice/bean/work_condition_entity.dart';
import 'package:jyofservice/bean/work_notice_detail_entity.dart';
import 'package:jyofservice/util/AesUtil.dart';
import 'package:jyofservice/util/webconfig.dart';

import 'LevelTree.dart';

class AddWorkConfition extends StatefulWidget {
  int? index;
  WorkConditionEntity? workConditionEntity;
  WorkNoticeDetailEntity? workNoticeDetailEntity;

  AddWorkConfition(
      {this.workConditionEntity, this.index, this.workNoticeDetailEntity});

  @override
  _AddWorkConfitionState createState() => _AddWorkConfitionState();
}

class _AddWorkConfitionState extends State<AddWorkConfition> {
  String chuliDate = "";
  String rangStr = "";
  TextEditingController stopWormTimController = TextEditingController();
  TextEditingController titleController = TextEditingController();
  TextEditingController contentController = TextEditingController();
  TextEditingController feeController = TextEditingController();
  List<Node> selectlist = [];
  bool isloading = false;
  List<DropdownMenuItem> typeList = [];


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (widget.index == 1 && widget.workConditionEntity != null) {
      chuliDate = widget.workConditionEntity!.endDt ?? '';
      rangStr = widget.workConditionEntity!.fanWeiName ?? '';
      stopWormTimController.text = widget.workConditionEntity!.lJStopTime!;
      titleController.text = widget.workConditionEntity!.title!;
      contentController.text = widget.workConditionEntity!.neiRong!;
      // feeController.text = widget.workNoticeDetailEntity!.data!.a!.fee!;

    }

    isloading = true;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          elevation: 0.0,
          centerTitle: true,
          title: Text('工况信息管理',
              style: TextStyle(
                  color: Colors.white, fontSize: ScreenUtil().setSp(45))),
          leading: IconButton(
              icon: Icon(Icons.arrow_back_ios),
              onPressed: () {
                Navigator.pop(context, false);
              }),
        ),
        body: Stack(
          alignment: Alignment(0.5, 0.5),
          children: <Widget>[
            Column(
              children: <Widget>[
                Expanded(
                  child: SingleChildScrollView(
                    child: Column(
                      children: <Widget>[
                        Container(
                            padding: EdgeInsets.only(left: 10, right: 10),
                            height: ScreenUtil().setHeight(100),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: <Widget>[
                                Icon(
                                  Icons.assignment,
                                  color: Colors.blue,
                                ),
                                Text(
                                  '工况信息',
                                  style: TextStyle(
                                      color: Colors.blue,
                                      fontSize: ScreenUtil().setSp(40)),
                                ),
                              ],
                            )),
                        Container(
                          padding: EdgeInsets.only(left: 10, right: 10),
                          color: Colors.black12,
                          height: 1,
                        ),
                        getChuLiTime(),
                        Container(
                          padding: EdgeInsets.only(left: 10, right: 10),
                          color: Colors.black12,
                          height: 1,
                        ),
                        getRange(),
                        Container(
                          padding: EdgeInsets.only(left: 10, right: 10),
                          color: Colors.black12,
                          height: 1,
                        ),
                        getInputContent('标        题', titleController),
                        Container(
                          padding: EdgeInsets.only(left: 10, right: 10),
                          color: Colors.black12,
                          height: 1,
                        ),
                        getInputContent('停暖时间(小时)', stopWormTimController),
                        Container(
                          padding: EdgeInsets.only(left: 10, right: 10),
                          color: Colors.black12,
                          height: 1,
                        ),
                        getChuLiNeiRong(),
                      ],
                    ),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    /** "Title": titleController.text,
                        "NeiRong": contentController.text,
                        "EndDt": chuliDate,
                        "LJStopTime": stopWormTimController.text,
                        "levelids": s,
                        "Fee":feeController.text.toString(),
                        "Type":typeId
                     *
                     */

                    if (widget.index == 0) {
                      if (selectlist.length > 0) {
                        addWork("DB/AddWorkInfo");
                      } else {
                        Fluttertoast.showToast(msg: "请选择发布范围");
                      }
                    } else {
                      addWork("DB/UpdateWorkInfo");
                    }
                  },
                  child: Container(
                    color: Colors.blue,
                    width: ScreenUtil().screenWidth,
                    child: Center(
                      child: Text(
                        '确认保存',
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: ScreenUtil().setSp(40)),
                      ),
                    ),
                    height: ScreenUtil().setHeight(100),
                  ),
                ),
                SizedBox(
                  height: ScreenUtil().bottomBarHeight,
                )
              ],
            ),
            Offstage(
              offstage: isloading,
              child: SpinKitFadingCircle(
                color: Colors.blue,
                size: 50.0,
              ),
            )
          ],
        ));
  }

  //处理内容
  Widget getJiaoFeNeiRong() {
    return Container(
      padding: EdgeInsets.only(left: 10, top: 10, right: 10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '维修费信息',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(50),
          ),
          Expanded(
              flex: 1,
              child: Container(
                height: ScreenUtil().setWidth(160),
                width: ScreenUtil().setWidth(500),
                color: Color(0xfff2f5f9),
                child: Container(
                  decoration: BoxDecoration(
                    border: Border.all(width: 1.0, color: Colors.black12),
                    borderRadius: BorderRadius.circular(2.5),
//                                               color: Colors.white,
                  ),
                  child: TextField(
                    textAlign: TextAlign.start,
                    maxLines: null,
                    onSubmitted: (text) {
                      //内容提交(按回车)的回调

                      print('submit $text');
                    },
                    controller: feeController,
                    textInputAction: TextInputAction.done,
                    decoration: InputDecoration(
                      fillColor: Color(0xfff2f5f9),
                      contentPadding: EdgeInsets.all(10.0),
                      border: InputBorder.none,
                    ),
                  ),
                ),
              )),
        ],
      ),
    );
  }

  //处理内容
  Widget getChuLiNeiRong() {
    return Container(
      padding: EdgeInsets.only(left: 10, top: 10, right: 10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '状况说明',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(50),
          ),
          Expanded(
              flex: 1,
              child: Container(
                height: ScreenUtil().setWidth(160),
                width: ScreenUtil().setWidth(500),
                color: Color(0xfff2f5f9),
                child: Container(
                  decoration: BoxDecoration(
                    border: Border.all(width: 1.0, color: Colors.black12),
                    borderRadius: BorderRadius.circular(2.5),
//                                               color: Colors.white,
                  ),
                  child: TextField(
                    textAlign: TextAlign.start,
                    maxLines: null,
                    onSubmitted: (text) {
                      //内容提交(按回车)的回调

                      print('submit $text');
                    },
                    controller: contentController,
                    textInputAction: TextInputAction.done,
                    decoration: InputDecoration(
                      fillColor: Color(0xfff2f5f9),
                      contentPadding: EdgeInsets.all(10.0),
                      border: InputBorder.none,
                    ),
                  ),
                ),
              )),
        ],
      ),
    );
  }

//  //输入内容
  Widget getInputContent(String title, TextEditingController controller) {
    return Container(
      padding: EdgeInsets.only(left: 10, right: 10),
      height: ScreenUtil().setHeight(120),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '$title',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(10),
          ),
          Expanded(
            flex: 1,
            child: Container(
                padding: EdgeInsets.only(left: 18),
//              height: ScreenUtil().setHeight(80),
                child: TextField(
                  controller: controller,
                  textAlign: TextAlign.start,
                  decoration: InputDecoration(
                    hintText: '请输入',
                    hintStyle: TextStyle(
                      color: Colors.grey,
                      fontSize: ScreenUtil().setSp(35),
                    ),
                    border: InputBorder.none,
                  ),
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: ScreenUtil().setSp(35),
                  ),
                )),
          ),
        ],
      ),
    );
  }

//影响范围
  Widget getRange() {
    return Container(
      padding: EdgeInsets.only(left: 10, right: 10),
      height: ScreenUtil().setHeight(120),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '影响范围',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(10),
          ),
          Expanded(
            flex: 1,
            child: Container(
              padding: EdgeInsets.all(2),
//              height: ScreenUtil().setHeight(80),
              child: Row(
                children: <Widget>[
                  TextButton(
                      onPressed: () {
                        Navigator.push(context,
                            new MaterialPageRoute(builder: (context) {
                          return LevelTree();
                        })).then((data) {
                          if (data != null) {
                            List<Node> se = data;
                            ;
                            selectlist.clear();
                            selectlist.addAll(se);
                            rangStr = "";
                            for (Node node in selectlist) {
                              rangStr += (node.type == Node.typeOrgan
                                      ? (node.object as Group).name
                                      : (node.object as Member).name)! +
                                  ",";
                            }
                            setState(() {});
                          }
                        });
                      },
                      child: Container(
                        width: ScreenUtil().setHeight(360),
                        padding: EdgeInsets.fromLTRB(0, 10, 10, 10),
                        child: Text(
                          rangStr.length > 0 ? rangStr : '请选择',
                          style: TextStyle(
                              color: Colors.grey,
                              fontSize: ScreenUtil().setSp(30)),
                        ),
                      )),
                ],
              ),
            ),
          ),
          Icon(
            Icons.keyboard_arrow_right,
            color: Color(0xff666666),
          )
        ],
      ),
    );
  }

  //处理时间
  Widget getChuLiTime() {
    return Container(
      padding: EdgeInsets.only(left: 10, right: 10),
      height: ScreenUtil().setHeight(120),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '截止时间',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(10),
          ),
          Expanded(
            flex: 1,
            child: Container(
              padding: EdgeInsets.all(2),
//              height: ScreenUtil().setHeight(80),
              child: Row(
                children: <Widget>[
                  TextButton(
                      onPressed: () {
                        DatePicker.showDateTimePicker(context,
                            showTitleActions: true, onChanged: (date) {
                          print('change $date');
                        }, onConfirm: (date) {
                          print('confirm $date');
                          setState(() {
                            chuliDate = date.toString().substring(0, 19);
                          });
                        }, currentTime: DateTime.now(), locale: LocaleType.zh);
                      },
                      child: Container(
                        width: ScreenUtil().setHeight(360),
                        padding: EdgeInsets.fromLTRB(0, 10, 10, 10),
                        child: Text(
                          chuliDate.length > 0 ? chuliDate : '请选择',
                          style: TextStyle(
                              color: Colors.grey,
                              fontSize: ScreenUtil().setSp(30)),
                        ),
                      )),
                ],
              ),
            ),
          ),
          Icon(
            Icons.keyboard_arrow_right,
            color: Color(0xff666666),
          )
        ],
      ),
    );
  }

  //新增工况
  Future addWork(String path) async {
    setState(() {
      isloading = false;
    });
    try {
      SharedPreferences sharedPreferences =
          await SharedPreferences.getInstance();
      String? key = sharedPreferences.getString("key");
      String aesData = await (AesUtil.encodeBase64());
      List s = [];

      if (rangStr.length != 0 && selectlist.length == 0 && widget.index == 1) {
        for (WorkNoticeDetailDataB? w in widget.workNoticeDetailEntity!.data!.b!) {
          var data = {"no": w!.levelID, "level": w.lev};
          s.add(data);
        }
      } else {
        for (Node node in selectlist) {
          var data = {
            "no": node.nodeId,
            "level": node.type == Node.typeOrgan
                ? (node.object as Group).levela
                : (node.object as Member).levela
          };
          s.add(data);
        }
      }
      var data = {
        "key": key,
        "ID": widget.index == 0 ? "" : widget.workConditionEntity!.iD.toString(),
        "Title": titleController.text.toString() ?? "",
        "NeiRong": contentController.text.toString() ?? "",
        "EndDt": chuliDate ?? "",
        "LJStopTime": stopWormTimController.text.toString() ?? "",
        "levelids": s,
        "ClientType": "phone",
        "ClientKey": aesData
      };
      print(json.encode(data));

      Response response =
          await Dio().post(WebConfig().baseUrl + path, data: data);
      print(response.data);
      Fluttertoast.showToast(msg: response.data["Msg"]);
      isloading = true;
      if (response.data["Code"] == "200") {
        Navigator.pop(context, true);
      } else {
        setState(() {});
      }
      return response.data;
    } catch (e) {
      if (mounted) {
        setState(() {
          isloading = true;
        });
      }
      print(e.toString());
      Fluttertoast.showToast(
        msg: "新增工况出错:${e.toString()}",
        toastLength: Toast.LENGTH_LONG,
        gravity: ToastGravity.CENTER,
      );
    }
  }

}
